package com.jinyang.jetpackdemo.activity

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.jinyang.jetpackdemo.R
import kotlinx.android.synthetic.main.activity_view_model.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class ViewModelActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_view_model)
        val userViewModel: UserViewModel = ViewModelProvider(
            this, ViewModelProvider.NewInstanceFactory()
//            this, ViewModelProvider.AndroidViewModelFactory(application)
        ).get(UserViewModel::class.java)
        userViewModel.userName.observe(this, Observer {
            tv_view_model.text=it
        })
        userViewModel.isLoading.observe(this, Observer {
            progressBar.visibility=if (it) View.VISIBLE else View.GONE
        })
        userViewModel.getUserName()
    }
}

//class MyViewModel(application: Application) : AndroidViewModel(application) {
class UserViewModel : ViewModel() {
    var userName: MutableLiveData<String> = MutableLiveData()
    var isLoading: MutableLiveData<Boolean> = MutableLiveData()
    fun getUserName() {
        isLoading.value = true
        GlobalScope.launch {
            delay(2000)
            isLoading.postValue(false)
            userName.postValue("欢迎关注公众号：今阳说")
        }
    }
}

class SharedViewModel :ViewModel(){
    var isReadFinish: MutableLiveData<Boolean> = MutableLiveData()
}
class DetailFragment  : Fragment(){
    fun onReadFinish(){
        val viewModel=ViewModelProvider(
            this, ViewModelProvider.NewInstanceFactory()
        ).get(SharedViewModel::class.java)
        viewModel.isReadFinish.value=true
    }
}
class ListFragment : Fragment(){
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val viewModel=ViewModelProvider(
            this, ViewModelProvider.NewInstanceFactory()
        ).get(SharedViewModel::class.java)
        viewModel.isReadFinish.observe(this, Observer {
            //更新列表UI
        })
    }
}
